﻿using SharpSvn;
using SharpSvn.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SharpSvnStart
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("program start.");
            Core();
            Console.WriteLine("program end.");
            Console.ReadLine();
        }

        private static void Core()
        {
            var outPath = "./Export";
            var url = "${svnUrl}";
            var ver = GetLatestRevision(url);
            Console.WriteLine("Export {0} to {1}", ver, outPath);
            var ok = ExportFile(Path.Combine(url, "Cortoi.DRClient"), "Program.cs", ver, outPath);

            Console.WriteLine("Export {0}", ok ? "success" : "failed");
        }

        public static long GetLatestRevision(string url)
        {
            using (SvnClient client = GetSvnClient())
            {
                SvnInfoEventArgs svnInfo;
                if (client.GetInfo(new SvnUriTarget(url), out svnInfo))
                {
                    return svnInfo.LastChangeRevision;
                }
                return 0;
            }
        }

        private static SvnClient GetSvnClient()
        {
            SvnClient client = new SvnClient();
            client.Authentication.Clear();
            client.Authentication.UserNamePasswordHandlers += Authentication_UserNamePasswordHandlers;
            client.Authentication.SslServerTrustHandlers += Authentication_SslServerTrustHandlers;
            return client;
        }

        private static void Authentication_SslServerTrustHandlers(object sender, SvnSslServerTrustEventArgs e)
        {
            e.AcceptedFailures = e.Failures;
            e.Save = true;
        }

        private static void Authentication_UserNamePasswordHandlers(object sender, SvnUserNamePasswordEventArgs e)
        {
            e.UserName = "${username}";
            e.Password = "${password}";
        }

        /// <summary>
        /// 导出指定版本的文件到本地
        /// </summary>
        public static bool ExportFile(string url, string filePath, long revision, string exportPath)
        {
            if (!Directory.Exists(exportPath))
            {
                Directory.CreateDirectory(exportPath);
            }
            exportPath = Path.Combine(exportPath, Path.GetFileName(filePath));
            using (SvnClient client = GetSvnClient())
            {
                return client.Export(new SvnUriTarget(Path.Combine(url, filePath), revision), exportPath);
            }
        }
    }
}
